package org.jiangy.authentication.config.problem;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.zalando.problem.Problem;
import org.zalando.problem.Status;
import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait;

/**
 * 安全相关的异常创建一个异常处理程序
 * <p>
 * <a href="https://github.com/zalando/problem-spring-web/tree/main/problem-spring-web#failsafe">An open circuit breaker will be translated into a 503 Service Unavailable</a>
 * <p>创建时间: 2024/8/16 </p>
 *
 * @author <a href="mailto:jiangliu0316@outlook.com" rel="nofollow">蒋勇</a>
 */
@Slf4j
@ControllerAdvice
public class SecurityExceptionHandler implements SecurityAdviceTrait {

    @ExceptionHandler(DataAccessException.class)
    public ResponseEntity<Problem> handleCustomException(DataAccessException ex) {
        log.error(ex.getMessage(), ex);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Problem.builder()
                        .withTitle("服务器发生内部错误")
                        .withStatus(Status.INTERNAL_SERVER_ERROR)
                        .build());
    }

    /**
     * 异常处理兜底策略
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Problem> handleException(Exception ex) {
        log.error(ex.getMessage(), ex);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Problem.builder()
                        .withTitle("服务器发生内部错误")
                        .withStatus(Status.INTERNAL_SERVER_ERROR)
                        .build());
    }
}
